<template>
  <el-container class="container">
    <!-- 左侧分类树 -->
    <el-aside width="240px" class="left-panel">

      <el-input
        v-model="searchKeyword"
        placeholder="选择分类"
        clearable
        @clear="loadImageList"
        @keyup.enter="loadImageList"
      />

      <el-tree
      style="margin-top: 10px;"
        ref="treeRef"
        node-key="id"
        :props="treeProps"
        :load="loadTreeNode"
        lazy
        highlight-current
        @node-click="handleNodeClick"
      />

    </el-aside>

    <!-- 右侧内容区 -->
    <el-main class="right-panel">
      <!-- 操作栏 -->
      <el-row class="toolbar" justify="space-between">
        <el-space>
          <el-button type="primary" @click="useSelected">使用选中图片</el-button>
           
          <!-- 点击上传图片按钮 -->
          <el-upload
              action="http://localhost:8301/admin/system/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers">
            <el-button><el-icon><Upload /></el-icon></el-button>
          </el-upload>

          <el-button @click="removeTP()" type="danger" :icon="Delete"  />

          <el-select v-model="moveTarget" placeholder="图片移动至">
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.categoryName"
              :value="category.id"
              @click="handleCategoryClick(category.id)" 
            />
          </el-select>
          
        </el-space>
        
        <el-space>
          <el-radio-group v-model="Image.isVideo" @click="aa()" @change="loadImageList">
            <el-radio-button
            v-for="item in [1,2]" 
              :key="item"
              :label="item">
          {{ ['图片','视频'][item-1] }}
            </el-radio-button>
          </el-radio-group>
        </el-space>

      </el-row>

      <!-- 图片列表 -->
      <el-row :gutter="16" class="image-grid">
  <el-col 
    v-for="item in imageList"
    :key="item.id"
    :xs="12" 
    :sm="8" 
    :md="6" 
    :lg="4.1"
  >
    <div 
      class="image-card"
      :class="{ 'selected': selectedIds.includes(item.id), 'shrink': selectedIds.includes(item.id) }"
      @click="toggleSelect(item)">
      <el-badge 
        v-if="selectedIds.includes(item.id)"
        :value="selectedIds.indexOf(item.id) + 1"
        type="primary"
        class="selection-badge"/>
      <el-image 
        :src="item.filePath"
        fit="cover"
        lazy
        class="preview-image"
      >
        <template #error>
          <div class="image-error">加载失败</div>
        </template>
      </el-image>
      <!-- <div class="file-name"> item.fileName </div> -->
    </div>
  </el-col>
</el-row>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        background
        @current-change="loadImageList"
      />
    </el-main>
  </el-container>
</template>

<script setup >
import { ref, onMounted } from 'vue'
import { GetImageList,SaveImpge,RemoveImpge,UpdateImageById} from 'src/service/api/material/Image.ts'
import { PictureById } from '@/api/picture.js'
import { useApp } from '@/pinia/modules/app'
import {Delete} from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'
//图片获取token
const headers = {
  token: useApp().authorization.token     // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

const aa=()=>{
  selectedIds.value = [];
  removeById.value= [];
}

const emit = defineEmits(['selectImage']) // 声明自定义事件


const handleCategoryClick=(id)=>{
  if(removeById.value.length>0){
    removeById.value.forEach(async (data) => {
      await UpdateImageById(data.id,id)
    })
    ElMessage.success('移动成功')
    
    selectedIds.value = []; // 清空选中状态
    removeById.value = []; // 清空已选择的图片 ID
    loadImageList();
  }else{
    moveTarget.value=''
    ElMessage.warning('请选择图片')
  }
}

const useSelected=()=>{
  if(removeById.value.length>0){
    removeById.value.forEach(async (data) => {
      emit('selectImage', data.filePath) // 注意.value
      console.log(data.filePath);
    })
    selectedIds.value = []; // 清空选中状态
    removeById.value = []; // 清空已选择的图片 ID
  }else{
    ElMessage.warning('请选择图片')
  }
}

// 图像上传成功以后的事件处理函数
const handleAvatarSuccess = async (response, uploadFile) => {
  Image.value.fileName = uploadFile.name // 原始文件名
  Image.value.filePath = response.data   // 假设后端返回存储路径
  Image.value.fileSize = uploadFile.size // 文件大小（字节）
  Image.value.mimeType = uploadFile.raw.type // MIME类型
  await SaveImpge(Image.value);
  ElMessage.success('保存成功')
  loadImageList();
}

// const beforeAvatarUpload = (rawFile) => {
//   // 示例：限制文件类型
//   const allowedTypes = ['image/jpeg', 'image/png', 'video/mp4']
//   if (!allowedTypes.includes(rawFile.type)) {
//     ElMessage.error('仅支持 JPG/PNG/MP4 格式')
//     return false
//   }
  
//   // 确保已选择分类
//   if (!currentCategoryId.value) {
//     ElMessage.error('请先选择分类')
//     return false
//   }
  
//   return true
// }

// 分类树配置
const treeRef = ref()
const treeProps = {
  label: 'categoryName',
  children: 'children',
  isLeaf: 'isLeaf'
}



// 图片数据
const imageList = ref([])
const selectedIds = ref([])
const moveTarget = ref()

const Image=ref({
  id:0,
  filePath:"",
  fileSize:"",
  mimeType:"",
  categoryId:"",
  isVideo:1
})

// 分类选项（用于移动）
const categoryOptions = ref([])

// 分页配置
const pagination = ref({
  current: 1,
  size: 8,
  total: 0
})

// 当前分类ID（默认-1表示全部）
const currentCategoryId = ref(-1)

// 删除
const removeTP=()=>{
  if(removeById.value.length!==0){
    ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning',
})
  .then(async () => {
    const removeId=ref([]);
    removeById.value.forEach(async (data) => {
       removeId.value.push(data.id)
    })
    await RemoveImpge(removeId.value);
    removeById.value=[];
    ElMessage.success('删除成功')
    selectedIds.value = []; // 清空选中状态
    removeById.value = []; // 清空已选择的图片 ID
    loadImageList()
  })
  .catch(() => {
    ElMessage.info('取消删除')
  })
  }else{
    ElMessage.warning('请选择图片')
  }
 
}

// 懒加载树节点数据
const loadTreeNode = async (node, resolve) => {
  try {
    // 根据节点层级获取父ID
    const parentId = node.level === 0 ? 0 : node.data.id
    
    // 调用API获取子分类
    const res = await PictureById( parentId )
    
    // 转换节点数据
    const nodes = res.data.map(item => ({
      ...item,
      isLeaf: !item.hasChildren  // 关键：根据hasChildren设置isLeaf
    }))

    // 首次加载时自动展开第一个节点
    if (node.level === 0 && nodes.length > 0) {
      treeRef.value.setCurrentKey(nodes[0].id)
    }
    resolve(nodes)
  } catch (error) {
    console.error('分类加载失败:', error)
    resolve([])
  }
}
// 加载图片列表
const loadImageList = async () => {
  try {
    const params = {
      page: pagination.value.current,
      limit: pagination.value.size,
      categoryId: currentCategoryId.value,
      isVideo: Image.value.isVideo
    }
    const res = await GetImageList(params)
    console.log(res);
    imageList.value = res.data.records
    pagination.value.total = res.data.total
    
    // 同时获取全部分类用于移动
    const allCates = await PictureById(0)
    categoryOptions.value = allCates.data
  } catch (error) {
    console.error('加载图片失败:', error)
  }
}

// 分类节点点击
const handleNodeClick = (data) => {
  Image.value.categoryId=data.id
  currentCategoryId.value = data.id === -1 ? -1 : data.id
  loadImageList()
}
const removeById=ref([])

// 切换选中状态
const toggleSelect = (item) => {
  const id=item.id;
  const indexById = removeById.value.findIndex(i => i.id === item.id);
  if (indexById !== -1) {
    // 如果存在，删除
    removeById.value.splice(indexById, 1); // 删除该索引位置的元素
  } else {
    // 如果不存在，添加
    removeById.value.push(item);
  }
  console.log(removeById.value);
  const index = selectedIds.value.indexOf(id);
   index > -1 ? selectedIds.value.splice(index, 1): selectedIds.value.push(id)
}

// 初始化加载
onMounted(() => {
  loadImageList()
})
</script>

<style scoped>


.container {
  height: 100%;
}

.left-panel {
  border-right: 1px solid var(--el-border-color);
  padding: 16px;
}

.image-grid {
  margin-top: 16px;
}

.image-card {
  position: relative;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 16px;
}



.image-card.selected {
  border: 1px solid var(--el-color-primary); /* 点击时边框变蓝 */
}

.image-card.shrink .preview-image {
  transform: scale(0.95); /* 点击时缩小图片内容 2% */
}

.preview-image {
  width: 100%;
  height: 150px;
  display: block;
  object-fit: cover;
  transition: transform 0.2s; /* 添加过渡效果 */
}

.file-name {
  padding: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.image-error {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-color-danger);
}

:deep(.el-tree-node__content) {
  height: 40px;
}

.selection-badge {
  position: absolute;
  bottom: 8px;
  right: 8px;
  z-index: 1;
}

:deep(.selection-badge .el-badge__content) {
  top: 8px;
  left: 8px;
  transform: none;
}
</style>